﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace QFramework.Example
{
	public class MySaverAndLoader : IItemKitSaverAndLoader
	    {
		    [Serializable]
		    public class SaveData
		    {
			    public List<GroupData> Groups;
		    }
		    
		    [Serializable]
		    public class GroupData
		    {
			    public string Key;
			    public List<SlotData> Slots;
		    }
		    
		    [Serializable]
		    public class SlotData
		    {
			    public string ItemKey;
			    public int Count;
		    }
		    
	        public void Save(Dictionary<string, SlotGroup> slotGroups)
	        {
		        var saveData = new SaveData()
		        {
			        Groups = slotGroups.Values.Select(group => new GroupData()
			        {
				        Key = group.Key,
				        Slots = group.Slots.Select(slot => new SlotData()
				        {
					        ItemKey = slot.Item != null ? slot.Item.GetKey : null,
					        Count = slot.Count,
				        }).ToList()
			        }).ToList()
		        };

		        var json = JsonUtility.ToJson(saveData);
		        PlayerPrefs.SetString("my_item_kit",json);
	        }
	        public void Load(Dictionary<string, SlotGroup> slotGroups)
	        {
	            // 读取所有SlotGroup的Key
	            var json = PlayerPrefs.GetString("my_item_kit", String.Empty);
	            if (json.IsNotNullAndEmpty())
	            {
		            // 把json转化成SlotGroupSaveData
		            var saveData = JsonUtility.FromJson<SaveData>(json);
		            
		            foreach (var group in saveData.Groups)
		            {
			            SlotGroup slotGroup = null;
			            if (slotGroups.ContainsKey(group.Key))
			            {
				            slotGroup = slotGroups[group.Key];
			            }else
			            {
				            slotGroup = ItemKit.CreateSlotGroup(group.Key);
			            }
			            
			            for (int i = 0; i < group.Slots.Count; i++)
			            {
				            var slotSaveData = group.Slots[i];
				            var item = slotSaveData.ItemKey.IsNullOrEmpty()?null:ItemKit.ItemByKey[slotSaveData.ItemKey];
				            // 如果存档中的slot数量大于SlotGroup中的数量，则需要创建新的Slot
				            if (i<slotGroup.Slots.Count)
				            {
					            slotGroup.Slots[i].Item = item;
					            slotGroup.Slots[i].Count = slotSaveData.Count;
					            slotGroup.Slots[i].Changed.Trigger();
				            }
				            else
				            {
					            slotGroup.CreateSlot(item, slotSaveData.Count);
				            }
			            }
		            }
	            }
	            
	            foreach (var slotGroup in slotGroups.Values)
	            {
	                
	            }
	        }

	        public void clear()
	        {
	            PlayerPrefs.DeleteKey("my_item_kit");
	        }
	    }
}